package com.interviews.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
     * 使用 ThreadLocal
 * 我们使用了 ThreadLocal 帮每个线程去生成它自己的 simpleDateFormat 对象，对于每个线程而言，这个对象是独享的。但与此同时，这个对象就不会创造过多，一共只有 16 个，因为线程只有 16 个。
 *
 * @author qian
 * @version 1.0
 * @date 2022/3/3 16:44
 */
public class ThreadLocalDemo06 {

    public static ExecutorService threadPool = new ThreadPoolExecutor(16, 16, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(), new ThreadLocalDemo03.ThreadLocalDemo03ThreadFactory("SimpleDateFormat06"));

    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            threadPool.submit(() -> {
                String date = new ThreadLocalDemo06().date(finalI);
                System.out.println(Thread.currentThread().getName() + "->\t" + date);
            });
        }
        threadPool.shutdown();
    }

    public String date(int seconds) {
        Date date = new Date(1000 * seconds);
        SimpleDateFormat dateFormat = ThreadSafeFormatter.dateFormatThreadLocal.get();
        return dateFormat.format(date);
    }
}

class ThreadSafeFormatter {
    public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("mm:ss"));
}
